﻿using ChuanYe.CountyFireManagement.Model;
using System;
using System.Collections.Generic;
using System.Text;

namespace ChuanYe.CountyFireManagement.BLL
{
    internal static class MySqlTools
    {
        public static string Limit(this RequestPageBase page)
        {
            int startRow = page.PageSize * (page.PageIndex - 1);
            string format = " limit {0},{1}";
            return string.Format(format, startRow, page.PageSize);
        }

        public static string OrderByDescending(this string key)
        {
            string format = " order by {0} desc ";
            return string.Format(format, key);
        }

        public static string OrderBy(this string key)
        {
            string format = " order by {0} asc ";
            return string.Format(format, key);
        }

        public static string CountSql(this string sql)
        {
            string result = string.Empty;
            sql = sql.ToLower();
            var start = sql.IndexOf("from");
            var end = -1;
            end = sql.IndexOf("order");
            if (end == -1)
            {
                end = sql.IndexOf("limit");
            }
            if (end == -1)
            {
                result = sql.Substring(start);
            }
            else
            {
                result = sql.Substring(start, end - start - 1);
            }
            return string.Format(" select count(1) as count {0} ", result);
        }

        public static string TimeSql(this RequestPageBase page,string columnName)
        {
            string sql = string.Empty;
            if (page.StartTime.HasValue)
            {
                sql += " and {0} >= '{1}'";
                sql = string.Format(sql,columnName ,page.StartTime.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            if (page.EndTime.HasValue)
            {
                sql += " and {0} <= '{1}'";
                sql = string.Format(sql,columnName ,page.EndTime.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            return sql;
        }




        public static string KeywordSql(this RequestPageBase page, string columnName) 
        {
            string sql = string.Empty;
            if (!string.IsNullOrEmpty(page.Keyword))
            {
                sql += " and {0} like '%{1}%'";
                sql = string.Format(sql, columnName, page.Keyword);
            }
            return sql;
        }

        public static string KeywordSql(this string value, string columnName,int andOr=0) 
        {
            string sql = string.Empty;
            if (!string.IsNullOrEmpty(value))
            {
                if (andOr == 0)
                {
                    sql += " and ";
                }
                else 
                {
                    sql += " or ";
                }
                sql += "  {0} like '%{1}%'";
                sql = string.Format(sql, columnName,value);
            }
            return sql;
        }
    }
}
